package com.example.user.controller;

import com.example.common.response.ResponseViewModel;
import com.example.user.entity.User;
import com.example.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/v1/api")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 1、添加用户
     */
    @PostMapping(value = "/user")
    public ResponseViewModel add() {
        User user = new User();
        user.setName("听风");
        user.setAge(25);
        user.setPhone("10010000");
        user.setCreateTime(new Date());
        Long id = userService.add(user);

        return new ResponseViewModel(id);
    }

    /**
     * 2、查询所有列表
     */
    @GetMapping("/users")
    public ResponseViewModel findAll() {
        ResponseViewModel model = new ResponseViewModel();
        model.setData(userService.getAll());
        return model;
    }

    /**
     * 3、分页查询
     */
    @GetMapping("/user/list")
    public ResponseViewModel findList(
            @RequestParam(name = "pageNum", required = false, defaultValue = "0") int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) {

        ResponseViewModel model = new ResponseViewModel();
        model.setData(userService.getList(pageNum, pageSize));
        return model;
    }

    /**
     * 4、查询详情
     */
    @GetMapping("/user/{id}")
    public ResponseViewModel findById(@PathVariable("id") long id) {
        return new ResponseViewModel(userService.findById(id));
    }

    /**
     * 5、更新
     */
    @PutMapping("/user/{id}")
    public ResponseViewModel update(@RequestParam("name") String name, @PathVariable("id") long id) {
        User user = new User();
        user.setName(name);
        user.setId(id);
        userService.updateById(user);

        return new ResponseViewModel(userService.findById(id));
    }

    /**
     * 6、删除
     */
    @DeleteMapping("/user/{id}")
    public ResponseViewModel deleteById(@PathVariable("id") long id) {
        return new ResponseViewModel(userService.deleteById(id));
    }

    /**
     * 7、删除
     */
    @DeleteMapping("/user")
    public ResponseViewModel deleteById(@RequestParam String ids) {
        // String 转换 List
        List<Long> idList = Arrays.asList(ids.split(",")).stream().map(id -> Long.valueOf(id)).collect(Collectors.toList());

        Integer effectNo = userService.deleteByIds(idList);
        System.out.println("受影响行数：" + effectNo);

        return new ResponseViewModel(effectNo);
    }


}
